package com.szgz.platform.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szgz.platform.config.SkipWrap;
import com.szgz.platform.result.ApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.szgz.platform")
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 跳过标注了 @SkipWrap 的类/方法
		if (returnType.getDeclaringClass().isAnnotationPresent(SkipWrap.class)
				|| (returnType.getMethod() != null && returnType.getMethod().isAnnotationPresent(SkipWrap.class))) {
			return false;
		}
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if (body == null) {
			return ApiResponse.success();
		}
		if (body instanceof ApiResponse) {
			return body;
		}
		// 字符串需要特殊处理
		if (body instanceof String) {
			try {
				return new ObjectMapper().writeValueAsString(ApiResponse.success(body));
			} catch (Exception e) {
				return body;
			}
		}
		return ApiResponse.success(body);
	}
}

